﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OnlineVideos.View_Models;
using OnlineVideos.Common;
using OnlineVideos.Data;
using OnlineVideos;
using Common.Library;
using System.Windows.Navigation;
using System.ComponentModel;
using OnlineVideos.UI;
using Microsoft.Phone.BackgroundAudio;

using OnlineVideos.Utilities;
using Common.Utilities;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using Microsoft.Phone.Shell;
using PicasaMobileInterface;

namespace OnlineMovies.Views
{
    public partial class StoryDetail : PhoneApplicationPage
    {
        string navigationvalue = string.Empty;
        string pivotindex = string.Empty;
        PivotItem currentItem = default(PivotItem);
        bool appbarvisible = true;
        bool IsBackgroundLoaded = false;
     
        public StoryDetail()
        {

            InitializeComponent();
            Loaded += new RoutedEventHandler(StoryDetails_Loaded);

            //if (AppSettings.ShowUniqueID != 0)
            //{
            //    pvtMainDetails.Background = ShowDetail.LoadShowPivotBackground(AppSettings.ShowUniqueID);
            //    tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
            //    IsBackgroundLoaded = true;
            //}

            LoadStoryIntro();
        }

        public void LoadStoryIntro()
        {
            try
            {
                string storyIntro = StoryManager.GetStoryIntro(AppSettings.ShowUniqueID.ToString(), 1);

                ShowList showDetail = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);

                if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && showDetail.SubTitle == Constants.MovieCategoryTelugu)
                {
                    tbstoryintro.FontFamily = new FontFamily("/Pothana2000.ttf#Pothana2000");
                    tbstoryintro.FontSize = 24;
                }
                if (showDetail.SubTitle == Constants.MovieCategoryEnglish)
                {
                    tbstoryintro.FontFamily = new FontFamily("/COM4NRG_.TTF#COM4t Nuvu Regular");
                    tbstoryintro.FontSize = 30;
                }
                if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && showDetail.SubTitle == Constants.MovieCategoryHindi)
                {
                    tbstoryintro.FontFamily = new FontFamily("/CDACOTYGB.TTF#CDAC-GISTYogesh");
                    tbstoryintro.FontSize = 24;
                }

                if (string.IsNullOrEmpty(storyIntro))
                {
                    txterror.Text = "story not available";
                    btnreadmore.Visibility = Visibility.Collapsed;
                    Record.Visibility = Visibility.Collapsed;
                    txterror.Visibility = Visibility.Visible;
                    btnreadmore.Visibility = Visibility.Collapsed;
                }
                else
                {
                    txterror.Visibility = Visibility.Collapsed;
                    btnreadmore.Visibility = Visibility.Visible;
                    Record.Visibility = Visibility.Visible;

                    if (!Task.Run(async () => await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
                    {
                        Record.Content = "Record Narration";
                    }
                    else
                    {
                        Record.Content = "Resume Narration";
                    }

                    tbstoryintro.Text = storyIntro;
                }
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadStoryIntro event In StoryDetail.cs file.", ex);
            }
        }

        private void LoadPivotThemes(long ShowID)
        {
            MainGrid.Background = ShowDetail.LoadShowPivotBackground(ShowID);

        }
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstackpl, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        void StoryDetails_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LoadAds();
                FlurryWP8SDK.Api.LogEvent("StoryDetail Page", true);
                int showid = AppSettings.ShowUniqueID;
                string sharedstatus = Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.ShareStatus;
                if (sharedstatus == "Shared To Blog")
                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Shared)";
                else
                    ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Not Shared)";
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status == "Custom")
                {

                    btnreadmore.Height = 70;
                    btnlisten.Height = 70;
                    Record.Height = 70;
                    Record.Margin = new Thickness(0, 291, 0, 15);
                    btnlisten.Margin = new Thickness(0, 422, 0, 0);
                }
                else
                {

                    btnreadmore.Height = 80;
                    btnlisten.Height = 80;
                    Record.Height = 80;
                    Record.Margin = new Thickness(0, 301, 0, 15);
                    btnlisten.Margin = new Thickness(0, 471, 0, 0);
                }
                btnreadmore.Content = "Read Story";
                btnlisten.Content = "Listen";



                if (Storage.DirectoryExists("/StoryRecordings/" + AppSettings.ShowID))
                {
                    this.btnlisten.Visibility = Visibility.Visible;
                }
                else
                {
                    this.btnlisten.Visibility = Visibility.Collapsed;
                }

                string id = "";
                if (NavigationContext.QueryString.TryGetValue("id", out id))
                    AppSettings.ShowID = id;

                if (IsBackgroundLoaded == false)
                {
                    LoadPivotThemes(AppSettings.ShowUniqueID);
                    tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title;
                }

                PageHelper.RemoveEntryFromBackStack("StoryDetails");
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in StoryDetails_Loaded event In StoryDetail.cs file.", ex);
            }
        }
        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("StoryDetail Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom event In StoryDetail.cs file.", ex);
            }
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                
                FlurryWP8SDK.Api.LogPageView();
                int showid = AppSettings.ShowUniqueID;
                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom")
                {
                    this.ApplicationBar.IsVisible = false;
                    appbarvisible = false;
                }
                else
                {
                    this.ApplicationBar.IsVisible = true;
                }
                if (NavigationContext.QueryString.TryGetValue("navigationvalue", out navigationvalue))
                {

                    if (navigationvalue == "1")
                    {
                        if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                            pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                        Constants.navigationvalue++;
                    }
                    else
                    {
                        if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                            pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                        Constants.navigationvalue--;
                    }
                    while (NavigationService.BackStack.Count() > 1)
                    {
                        if (!NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("StoryDetails"))
                        {
                            NavigationService.RemoveBackEntry();
                        }
                        else
                        {
                            NavigationService.RemoveBackEntry();
                            break;
                        }
                    }
                }
                if (showVideoList.lbxSongsList.IsEnabled == false)
                    showVideoList.lbxSongsList.IsEnabled = true;

                //YouTube.CancelPlay();
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo event In StoryDetail.cs file.", ex);
            }
        }

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            ////if (YouTube.CancelPlay())
            //    e.Cancel = true;

            base.OnBackKeyPress(e);
        }

        private void btnreadmore_Click(object sender, RoutedEventArgs e)
        {
            Constants.mode = "Read";
            NavigationService.Navigate(NavigationHelper.StoryReadingPage);
        }
        private void btnbtnlisten_Click(object sender, RoutedEventArgs e)
        {

            Constants.mode = "Listen";
            NavigationService.Navigate(NavigationHelper.StoryReadingPage);
        }

        private void btnrecard_Click(object sender, RoutedEventArgs e)
        {

            if (!Storage.DirectoryExists("StoryRecordings"))
                Storage.CreateDirectory("StoryRecordings");
            Constants.mode = "Rec";
            NavigationService.Navigate(NavigationHelper.StoryReadingPage);
        }
        private void btnshare_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (NetworkHelper.IsNetworkAvailableForDownloads())
                {
                    UploadToBlog upload = new UploadToBlog(AppSettings.ShowUniqueID, page1: this);
                }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in btnshare_Click_1 event In StoryDetail.cs file.", ex);
            }

        }

        private void btnadd_Click_1(object sender, EventArgs e)
        {


            try
            {
                if ((sender as ApplicationBarMenuItem).Text.Contains("videos"))
                {
                    Constants.DownloadTimer.Stop();
                    Constants.Linkstype = "Songs";
                    NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=" + string.Empty, UriKind.Relative));
                }
                if ((sender as ApplicationBarMenuItem).Text.Contains("story"))
                {
                    if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                        NavigationService.Navigate(new Uri("/Views/Story.xaml?PageName=StoryDetails.xaml", UriKind.Relative));
                    else if (ResourceHelper.AppName == Apps.Vedic_Library.ToString())
                        NavigationService.Navigate(new Uri("/Views/Story.xaml?PageName=VedicDetails.xaml", UriKind.Relative));
                }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in btnadd_Click_1 event In StoryDetail.cs file.", ex);
            }

        }

        private void pvtMainDetails_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                currentItem = e.AddedItems[0] as PivotItem;
                if (appbarvisible == true)
                {
                    if (currentItem != null)
                    {
                        if (currentItem.Header.ToString() == "videos")
                        {
                            if (this.ApplicationBar.MenuItems.Count == 3)
                                this.ApplicationBar.MenuItems.RemoveAt(2);
                            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add" + " " + currentItem.Header.ToString();

                        }

                        else
                        {
                            if (this.ApplicationBar.MenuItems.Count < 3)
                            {
                                ApplicationBarMenuItem appBarMenuitem = new ApplicationBarMenuItem("Edit" + " " + "story");
                                appBarMenuitem.Click += btnedit_Click_1;
                                this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add" + " " + "story";
                            }

                            //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = true;

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in pvtMainDetails_SelectionChanged_1 event In StoryDetail.cs file.", ex);
            }
        }

        private void btnedit_Click_1(object sender, EventArgs e)
        {

            NavigationService.Navigate(new Uri("/Views/EditStory.xaml", UriKind.Relative));
        }
    }
}